package dao

import (
	"lib/log"
	"lib/structs/ams"
	"lib/structs/enum"
	"lib/structs/tables"
	"sync"
)

var LogMapCache sync.Map     // 需要上报的信息缓存，避免频繁查询数据库,map[id]tables.ClientAmsLog
var PolicyMap sync.Map       // 策略和上一次执行策略的时间 ,map[tables.ClientAmsPolicy]int64
var PolicyResultMap sync.Map // 策略执行结果的映射，map[policyId]tables.ClientAmsLog
var BootTime int64           // 程序启动时间，不要重置这个值，因为数据库写入时做了按天分割。不重置还能方便统计长时间不关机的情况

var (
	// 数据库中的配置项，开发阶段读取配置文件，正式环境使用数据库读取配置

	LogLv          string
	AmsCode        string
	UniqueType     string
	HandsUpArgus   string
	GuarderArgus   string
	FileServerAddr string
)

func LoadCache() (err error) {
	// 加载数据库中的基础配置
	var configList []tables.ClientAmsConfig
	err = DB.Find(&configList).Error
	if err != nil {
		return
	}
	for _, item := range configList {
		switch item.Key {
		case ams.ConfigKeyForLog:
			log.ResetLv(item.Val)
			LogLv = item.Val
		case ams.ConfigKeyForAmsCode:
			AmsCode = item.Val
		case ams.ConfigKeyForUniqueType:
			UniqueType = item.Val
		case ams.ConfigKeyForHandsUp:
			HandsUpArgus = item.Val
		case ams.ConfigKeyForGuarder:
			GuarderArgus = item.Val
		case ams.ConfigKeyForFileServer:
			FileServerAddr = item.Val
		}
	}
	if UniqueType == "" {
		UniqueType = "bios+disk"
	}

	// 加载策略和策略对应的最后一条日志时间
	var li2 []tables.ClientAmsPolicy
	if err = DB.Find(&li2).Error; err != nil {
		return err
	}
	logIds := make([]int64, 0)
	for _, item := range li2 {
		var al tables.ClientAmsLog
		err = DB.Where(&tables.ClientAmsLog{LogCode: item.ResCode, Ack: enum.No}).
			Order("create_at desc").Limit(1).Find(&al).Error
		if err != nil {
			return err
		}
		logIds = append(logIds, al.Id)
		LogMapCache.Store(al.Id, al)
		PolicyMap.Store(item, al.CreateAt)
	}
	var logList []tables.ClientAmsLog
	// 加载全部日志
	err = DB.Where("ack = ? and id not in ?", enum.No, logIds).Find(&logList).Error
	if err != nil {
		return err
	}
	for _, item := range logList {
		LogMapCache.Store(item.Id, item)
	}
	return err
}
